<template>
	<view class="outsize">
		<scroll-view scroll-y="true" class="scroll-wrapper">
			<view class="heard" style="margin-top: 0;">
				请上传身份证的正反面
			</view>
			<view class="outsizeUp" style="padding: 14px 14px;">
				<view
					style="display: flex;background-color: #FFF9E9;justify-content: space-between;padding: 5px 5px 0;border-radius: 8px;">
					<view style="margin-right: auto;">
						头像面
						<view style="color: #999999;font-size: 12px;margin-top: 2px;">
							上传身份证头像面
						</view>
					</view>
					<view class="">
						<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
							:maxCount="1"></u-upload>
					</view>
				</view>
				<view
					style="display: flex;background-color: #FFF9E9;justify-content: space-between;padding: 5px 5px 0;margin-top: 14px;border-radius: 8px;">
					<view style="margin-right: auto;">
						国徽面
						<view style="color: #999999;font-size: 12px;margin-top: 2px;">
							上传身份证国徽面
						</view>
					</view>
					<view class="">
						<u-upload :fileList="fileList2" @afterRead="afterRead2" @delete="deletePic2" name="1" multiple
							:maxCount="1"></u-upload>
					</view>
				</view>
			</view>
			<view class="heard">
				请填写信息
			</view>
			<view class="outsizedomn">
				<u-cell-group>
					<u-cell title="姓名">
						<template #value>
							<u-input inputAlign='right' placeholder='您的真实姓名' border='none' :disabled='optional'
								v-model="tableContent.realName"></u-input>
						</template>
					</u-cell>
					<u-cell title="身份证地址">
						<template #value>
							<u-input inputAlign='right' placeholder='请填写您的详细地址' border='none' :disabled='optional'
								v-model="tableContent.address"></u-input>
						</template>
					</u-cell>
					<u-cell title="身份证号码">
						<template #value>
							<u-input inputAlign='right' placeholder='您的身份证' border='none' :disabled='optional'
								v-model="tableContent.idCard"></u-input>
						</template>
					</u-cell>
					<u-cell title="身份证有效期">
						<template #value>
							<view style="display: flex;">
								<view style="width: 80px;" @click="nihh">
									<u-input inputAlign='center' placeholder='开始时间' border='none' v-model="front"
										:disabled='optional' disabled='true' disabledColor="#ffffff"></u-input>
								</view>
								<view class="">
									—
								</view>
								<view style="width: 80px;" @click="nihh2">
									<u-input inputAlign='center' placeholder='截至时间' border='none' v-model="back"
										:disabled='optional' disabled='true' disabledColor="#ffffff"></u-input>
								</view>
							</view>
						</template>
					</u-cell>
					<u-cell title="开户行名称" v-if="tableContent.authStatus==1">
						<template #value>
							<u-input inputAlign='right' placeholder='您的开户行名称' border='none' :disabled='optional'
								v-model="tableContent.bankName"></u-input>
						</template>
					</u-cell>
					<u-cell title="银行账号" v-if="tableContent.authStatus==1">
						<template #value>
							<u-input inputAlign='right' placeholder='您的银行账号' border='none' :cursor-spacing="juli"
								:disabled='optional' style="position: relative;"
								v-model="tableContent.bankCard"></u-input>
							<view style="position: absolute;left: 14px;font-size: 10px; color: red;">
								注：上传房源有分润
							</view>
							<!-- <u-input border="borderss" placeholder="请输入钥匙管理者的身份证" v-model="" type="number"></u-input> -->
						</template>
					</u-cell>
					<u-datetime-picker hasInput :show="show1" v-model="value1" mode="date" @cancel='show1=false'
						:minDate="0" @confirm='timeone'></u-datetime-picker>
					<u-datetime-picker hasInput :show="show2" v-model="value2" mode="date" @cancel='show2=false'
						@confirm='timeone2'></u-datetime-picker>
					<u-cell title="手机号码">
						<template #value>
							<u-input inputAlign='right' placeholder='您的手机号码' border='none'
								v-model="tableContent.phonenumber"></u-input>
						</template>
					</u-cell>
				</u-cell-group>
			</view>
			<!-- <view hidden="true" class="outsizedomnOne">
				<u-cell-group>
				
				</u-cell-group>
			</view> -->
			<view class="heard">
				<button @click="submit"
					style="border: none;background-color: #FFDA00;border-radius: 10px;font-size: 15px;">
					提交
				</button>
			</view>
		</scroll-view>
		<u-picker :show="show" :columns="columns" @confirm="confirm" @cancel="show=false" keyName="label"></u-picker>
		<u-picker :show="showtwo" :columns="columnstwo" @confirm="confirmtwo" @cancel="showtwo=false"
			keyName="label"></u-picker>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue';
	import {
		get,
		post
	} from '@/serve/method.js'
	import {
		urlHead
	} from "@/serve/serve.js" // 全局配置文件
	import {
		test
	} from '@/uni_modules/uview-plus';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	// const borderss = ref(false)
	// const juli = ref(0)
	// onLoad((option) => {
	// 	console.log(option, 999999999)
	// 	tableContent.authStatus = option.id
	// })
	const optional = ref(false)
	const tableContent = reactive({
		representes: '', //是否可以代表房东签约
		legalValidity: '', //证件有效日期
		bankCard: '', //银行卡号
		bankName: '', //开户行名称
		merName: '', //虚拟商户名称
		address: '', //地址
		type: '', //证件类型
		idCard: '', //身份证号
		phonenumber: '', //手机号
		idFrontUrl: '', //身份证正面地址
		idVersoUrl: '', //身份证反面地址
		realName: '', //实际收租人
		authStatus: "2",
		userId: '',
	})
	// 证件有效日期选择框
	const show2 = ref(false);
	const value2 = ref(Date.now());
	const nihh2 = () => {
		show2.value = true
	}
	const back = ref()
	const timeone2 = (item) => {
		show2.value = false
		let date = new Date(item.value);
		let year = date.getFullYear();
		let month = (date.getMonth() + 1).toString().padStart(2, '0');
		let day = date.getDate().toString().padStart(2, '0');
		back.value = `${year}${month}${day}`
		console.log(`${year}${month}${day}`, 88888888888888)
	}
	const front = ref()
	const show1 = ref(false);
	const value1 = ref(Date.now());
	const nihh = () => {
		show1.value = true
	}
	const timeone = (item) => {
		show1.value = false
		let date = new Date(item.value);
		let year = date.getFullYear();
		let month = (date.getMonth() + 1).toString().padStart(2, '0');
		let day = date.getDate().toString().padStart(2, '0');
		front.value = `${year}${month}${day}`
		console.log(front.value, 88888888888888)
	}
	// 
	// 证件类型
	const leixing = ref()
	const onepick = () => {
		show.value = true
	}
	const show = ref(false);
	const columns = reactive([
		[{
				label: '身份证',
				id: 1
			},
			{
				label: '护照',
				id: 2
			}
		]
	]);
	const confirm = (e) => {
		console.log('confirm', e.value[0]);
		leixing.value = e.value[0].label
		tableContent.type = e.value[0].id
		show.value = false;
	};
	// 
	// 选择框是否可以代表房东签约
	const twopick = () => {
		showtwo.value = true
	}
	const nengfou = ref()
	const showtwo = ref(false);
	const columnstwo = reactive([
		[{
				label: '是',
				id: 1
			},
			{
				label: '否',
				id: 0
			}
		]
	]);
	const confirmtwo = (e) => {
		console.log('confirm', e);
		nengfou.value = e.value[0].label
		tableContent.representes = e.value[0].id
		showtwo.value = false;
	};
	// 
	const action = ref(urlHead + '/common/upload')
	// 头像面
	const fileList1 = ref([])
	const deletePic = (event) => {
		fileList1.value.splice(event.index, 1);
	}
	const afterRead = async (event) => {
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = fileList1.value.length;
		lists.map((item) => {
			fileList1.value.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			console.log(lists[i].url, 7777)
			const result = await uploadFilePromise(lists[i].url);
			let item = fileList1.value[fileListLen];
			fileList1.value.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
			tableContent.idFrontUrl = fileList1.value[0].url
			console.log(fileList1.value, '图片总')
			let url = '/api/user/getAccessToken'
			get(url, {
				imgUrl: tableContent.idFrontUrl
			}).then((res) => {
				console.log(res.data, 77878787)
				console.log(JSON.parse(res.data), 8888)
				if (JSON.parse(res.data).errcode == 0) {
					optional.value = true
					tableContent.realName = JSON.parse(res.data).name
					tableContent.address = JSON.parse(res.data).addr
					tableContent.idCard = JSON.parse(res.data).id
				}
			})
			// uni.request({
			// 	url: 'https://api.weixin.qq.com/cgi-bin/token', // 你的API接口地址
			// 	method: 'GET',
			// 	data: {
			// 		"grant_type": "client_credential",
			// 		"appid": "wx5c1dd15bc7f074ee",
			// 		"secret": "dc7ba37c44ac57c73712a11923401d6b"
			// 	},
			// 	success: function(res) {
			// 		console.log(res.data);
			// 		let access_token = res.data.access_token
			// 		uni.request({
			// 			url: `https://api.weixin.qq.com/cv/ocr/idcard?type=photo&img_url=${tableContent.idFrontUrl}&access_token=${access_token}`, // 你的API接口地址
			// 			method: 'POST',
			// 			success: function(res) {
			// 				console.log(res.data);
			// 				tableContent.realName = res.data.name
			// 				tableContent.address = res.data.addr
			// 				tableContent.idCard = res.data.id
			// 			},
			// 			fail: function(error) {
			// 				console.error(error);
			// 			}
			// 		});
			// 	},
			// 	fail: function(error) {
			// 		console.error(error);
			// 	}
			// });
		}
	}
	// 国徽面
	const fileList2 = ref([])
	const deletePic2 = (event) => {
		fileList2.value.splice(event.index, 1);
	}
	const afterRead2 = async (event) => {
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = fileList2.value.length;
		lists.map((item) => {
			fileList2.value.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			console.log(lists[i].url, 7777)
			const result = await uploadFilePromise(lists[i].url);
			let item = fileList2.value[fileListLen];
			fileList2.value.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
			tableContent.idVersoUrl = fileList2.value[0].url
			console.log(fileList2.value, '图片总')
			let url = '/api/user/getAccessToken'
			get(url, {
				imgUrl: tableContent.idVersoUrl
			}).then((res) => {
				console.log(res.data, 77878787)
				if (JSON.parse(res.data).errcode == 0) {
					let one = JSON.parse(res.data).valid_date.split('-')
					console.log(one, 8989898)
					front.value = one[0]
					back.value = one[1]
				}
			})
		}
	}
	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: action.value,
				filePath: url,
				name: 'file',
				formData: {
					user: 'test',
				},
				success: (res) => {
					console.log(JSON.parse(res.data).url, '图片')
					if (JSON.parse(res.data).url == undefined) {
						return uni.showModal({
							title: '提示',
							content: '图片上传失败，请联系管理员',
							showCancel: false,
							success: function(resoo) {
								fileList1.value.length = 0
								fileList2.value.length = 0
							}
						});
					}
					setTimeout(() => {
						resolve(JSON.parse(res.data).url);
					}, 1000);
				},
				fail(res) {
					console.log(res, '失败')
				}
			});
		});
	}
	// // 银行卡校验
	// const validateBankCard = (cardNumber) => {
	// 	// 简化的Luhn算法检查
	// 	var sum = 0;
	// 	var digit;
	// 	var shouldDouble = false;

	// 	for (var i = cardNumber.length - 1; i >= 0; i--) {
	// 		digit = cardNumber.substring(i, (i + 1));
	// 		digit = parseInt(digit, 10);

	// 		if (shouldDouble) {
	// 			digit *= 2;
	// 			if (digit > 9) {
	// 				digit -= 9;
	// 			}
	// 		}

	// 		sum += digit;
	// 		shouldDouble = !shouldDouble;
	// 	}

	// 	return (sum % 10) === 0;
	// }
	// 电话号码校验
	const isValidPhoneNumber = (phoneNumber) => {
		const regex = /^1[3-9]\d{9}$/;
		return regex.test(phoneNumber);
	}
	// 提交
	const submit = () => {
		if (test.isEmpty(tableContent.idFrontUrl)) {
			return wx.showToast({
				title: '请上传身份证正面照片',
				icon: 'none',
				duration: 2000
			})
		}
		if (test.isEmpty(tableContent.idVersoUrl)) {
			return wx.showToast({
				title: '请上传身份证反面照片',
				icon: 'none',
				duration: 2000
			})
		}
		if (test.isEmpty(tableContent.realName)) {
			return wx.showToast({
				title: '请输入您的真实姓名',
				icon: 'none',
				duration: 2000
			})
		}
		if (test.isEmpty(tableContent.address)) {
			return wx.showToast({
				title: '请输入您的身份证地址',
				icon: 'none',
				duration: 2000
			})
		}
		// if (test.isEmpty(tableContent.type)) {
		// 	return wx.showToast({
		// 		title: '请选择您的证件类型',
		// 		icon: 'none',
		// 		duration: 2000
		// 	})
		// }
		if (!test.idCard(tableContent.idCard)) {
			return wx.showToast({
				title: '请输入正确的身份证号',
				icon: 'none',
				duration: 2000
			})
		}
		if (test.isEmpty(front.value)) {
			return wx.showToast({
				title: '请输入身份证有效期开始时间',
				icon: 'none',
				duration: 2000
			})
		}
		// if (test.isEmpty(back.value)) {
		// 	return wx.showToast({
		// 		title: '请输入身份证有效期结束时间',
		// 		icon: 'none',
		// 		duration: 2000
		// 	})
		// }
		if (!isValidPhoneNumber(tableContent.phonenumber)) {
			console.log(22222)
			return wx.showToast({
				title: '请输入正确的手机号',
				icon: 'none',
				duration: 2000
			})
		}
		// if (test.isEmpty(tableContent.bankName)) {
		// 	return wx.showToast({
		// 		title: '请输入您的开户行名称',
		// 		icon: 'none',
		// 		duration: 2000
		// 	})
		// }
		// if (!validateBankCard(tableContent.bankCard)) {
		// 	return wx.showToast({
		// 		title: '请输入正确的银行卡号',
		// 		icon: 'none',
		// 		duration: 2000
		// 	})
		// }
		uni.getStorage({
			key: 'lifeData',
			success: function(res) {
				tableContent.legalValidity = `${front.value}-${back.value}`
				console.log(tableContent.legalValidity, 888889898)
				tableContent.userId = res.data.vuex_user.userId
				let url = '/api/user/registerUser'
				post(url, tableContent).then((res) => {
					console.log(res, 88888)
					if (res.msg == "身份认证提交审核成功") {
						uni.redirectTo({
							url: '/pages/mine/succer/succer'
						});
					}
				})
			},
			fail: function(res) {
				if (res.errMsg == 'getStorage:fail data not found') {
					uni.reLaunch({
						url: '/pages/index/index'
					});
				}
			}
		})
	}
</script>

<style scoped lang="scss">
	.outsize {
		.scroll-wrapper {
			position: absolute;
			width: calc(100vw - 20px);
			background-color: #F2F2F2;
			padding: 20px 10px;
			height: calc(100vh - 40px);
		}

		.heard {
			margin-left: 5vw;
			color: #999999;
			font-size: 12px;
			// margin: 20px 20px;
			margin: 15px 0;
		}

		.outsizeUp {
			// width: 100%;
			background-color: #ffffff;
			border-radius: 5px;
		}

		.outsizedomn {
			width: 100%;
			background-color: #ffffff;
			border-radius: 5px;
		}

		.outsizedomnOne {
			margin-top: 10px;
			margin-bottom: 10px;
			badding-bottom: 10px;
			width: 100%;
			background-color: #ffffff;
			border-radius: 5px;
		}
	}
</style>